package com.qiu.greened.ui.post

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.lwkandroid.imagepicker.ImagePicker
import com.lwkandroid.imagepicker.data.ImageBean
import com.lwkandroid.imagepicker.data.ImagePickType
import com.lwkandroid.widget.ngv.DefaultNgvAdapter
import com.lwkandroid.widget.ngv.DefaultNgvAdapter.OnChildClickedListener
import com.lwkandroid.widget.ngv.INgvImageLoader
import com.lwkandroid.widget.ngv.NgvChildImageView
import com.qiu.greened.R
import com.qiu.greened.bean.PostDto
import com.qiu.greened.databinding.ActivityPostAddBinding
import com.qiu.greened.network.PostService
import com.qiu.greened.network.ServiceCreator
import com.qiu.greened.network.UserService
import com.qiu.greened.utils.MyData
import com.qiu.greened.utils.showToast
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


class PostAddActivity : AppCompatActivity() {

    private lateinit var binding: ActivityPostAddBinding
    private lateinit var ngvAdapter: DefaultNgvAdapter<ImageBean>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPostAddBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //标题栏
        supportActionBar?.let {
            it.setHomeButtonEnabled(true)
            it.setDisplayHomeAsUpEnabled(true)
            it.title = "发布动态"
        }
        setImage()

    }

    fun setImage() {
        //图片
        binding.gridView.setEnableEditMode(true)
        binding.gridView.setIconPlusDrawable(R.drawable.ic_baseline_add_24)
        binding.gridView.setIconDeleteDrawable(R.drawable.ic_ngv_delete)
        //创建图片加载器
        class GlideDisplay : INgvImageLoader<ImageBean> {
            override fun load(imageBean: ImageBean, imageView: ImageView, width: Int, height: Int) {
                Glide.with(imageView.context)
                    .load(imageBean.imagePath)
                    .apply(RequestOptions().override(width, height))
                    .into(imageView)
            }
        }
        //NineGridView的数据适配器，构造方法中必须设置最大数据容量和图片加载器
        ngvAdapter = DefaultNgvAdapter(9, GlideDisplay())
        ngvAdapter.setOnChildClickListener(object : OnChildClickedListener<ImageBean> {
            override fun onPlusImageClicked(plusImageView: ImageView, dValueToLimited: Int) {
                ImagePicker()
                    .pickType(ImagePickType.MULTI) //设置选取类型(拍照ONLY_CAMERA、单选SINGLE、多选MULTI)
                    .maxNum(dValueToLimited) //设置最大选择数量(此选项只对多选生效，拍照和单选都是1，修改后也无效)
                    .needCamera(true) //是否需要在界面中显示相机入口(类似微信那样)
                    .start(this@PostAddActivity, 200) //自定义RequestCode
            }

            override fun onContentImageClicked(
                position: Int, data: ImageBean, childImageView: NgvChildImageView?
            ) {
                Log.d("image", data.imagePath)
                //点击图片时的回调
            }

            override fun onImageDeleted(position: Int, data: ImageBean) {
                //点击删除按钮后的回调
            }
        })
        binding.gridView.adapter = ngvAdapter
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 200 && resultCode == RESULT_OK && data != null) {
            //获取选择的图片数据
            val list: List<ImageBean> =
                data.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA)!!
            ngvAdapter.addDataList(list)
        }
    }

    private fun sand(text: String) {
        lifecycleScope.launch {
            try {
                val dataList = ngvAdapter.dataList
                val imgList: ArrayList<String> = ArrayList()
                dataList.forEach {
                    val file = File(it.imagePath)
                    val requestFile = RequestBody.create(MediaType.parse("image/jpg"), file)
                    val body = MultipartBody.Part.createFormData("image", file.name, requestFile)
                    val upload = ServiceCreator.create<UserService>().upload(MyData.token, body)
                    if (upload.code == 200) {
                        imgList.add(upload.msg)
                    }
                }
                val joinToString = imgList.joinToString(separator = "&")
                Log.d("image", joinToString)
                val post = PostDto(MyData.userId, text, joinToString)
                val result = ServiceCreator.create<PostService>().addPost(MyData.token, post)
                if (result.code == 200) {
                    "发布成功".showToast()
                    finish()
                }
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(applicationContext, "${e.message}", Toast.LENGTH_SHORT).show()
                Log.i("请求失败", "${e.message}")
            }
        }
    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        val inflater = menuInflater
        inflater.inflate(R.menu.post_add_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> {
                finish() // back button
                return true
            }
            R.id.sand -> {
                val text = binding.editContent.text.toString()
                if (text == "") {
                    "请输入内容".showToast()
                } else {
                    sand(text)
                }
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }
}